<template>
  <div class="user-container">
    <Splitpanes class="default-theme hs">
      <Pane size="20">
        <div style="width: 100%; padding: 10px">
          <div
            style="padding: 20px; color: #000; border-bottom: 1px solid #f4f5f6"
          >
            组织机构
          </div>
          <div class="container" :style="'height:' + height + 'px;'">
            <el-scrollbar>
              <el-tree
                ref="deptRef"
                node-key="id"
                :load="loadNode"
                lazy
                :props="{
                  children: 'children',
                  label: 'name',
                  isLeaf: 'leaf',
                }"
                current-node-key
                highlight-current
                :expand-on-click-node="false"
                @node-click="handleNodeClick"
              />
            </el-scrollbar>
          </div>
        </div>
      </Pane>
      <Pane>
        <div style="width: 100%; padding: 10px">
          <vxe-grid
            ref="xGrid"
            border
            stripe
            keep-source
            auto-resize
            sync-resize
            :height="height"
            :loading="listLoading"
            :column-config="{ resizable: true }"
            :export-config="{}"
            :columns="tableColumn"
            align="center"
            :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
            :seq-config="{ seqMethod: seqMethod }"
          >
            <template #form>
              <vxe-form
                ref="queryform"
                title-align="right"
                title-width="130"
                prevent-submit
                title-colon
              >
                <vxe-form-item title="账号" span="8">
                  <template #default>
                    <el-input
                      v-model="queryForm.username"
                      placeholder="请输入账号"
                      style="width: 200px"
                      clearable
                    />
                  </template>
                </vxe-form-item>
                <vxe-form-item title="用户昵称" span="8">
                  <template #default>
                    <el-input
                      v-model="queryForm.nickName"
                      placeholder="请输入用户昵称"
                      style="width: 200px"
                      clearable
                    />
                  </template>
                </vxe-form-item>
                <vxe-form-item title="状态" span="8">
                  <template #default>
                    <el-select
                      v-model="queryForm.status"
                      class="filter-item"
                      placeholder="请选择"
                      style="width: 120px"
                      clearable
                    >
                      <el-option
                        v-for="item in statusList"
                        :key="item.key"
                        :label="item.display_name"
                        :value="item.key"
                      />
                    </el-select>
                  </template>
                </vxe-form-item>
                <vxe-form-item span="24" align="center">
                  <el-button :icon="Search" @click="queryData">搜索</el-button>
                  <el-button
                    v-permissions="{ permission: ['system:user:create'] }"
                    class="filter-item"
                    type="primary"
                    plain
                    :icon="Plus"
                    @click="handleEdit('add')"
                  >
                    新增
                  </el-button>
                  <el-button
                    v-permissions="{ permission: ['system:user:update'] }"
                    type="success"
                    plain
                    :icon="Edit"
                    @click="handleEdit('edit')"
                  >
                    编辑
                  </el-button>
                  <el-button
                    v-permissions="{ permission: ['system:user:delete'] }"
                    type="danger"
                    plain
                    :icon="Delete"
                    @click="handleDelete()"
                  >
                    删除
                  </el-button>
                  <el-button
                    v-permissions="{
                      permission: ['system:user:update-password'],
                    }"
                    type="danger"
                    plain
                    :icon="MagicStick"
                    @click="pwdReset()"
                  >
                    密码重置
                  </el-button>
                  <el-button
                    v-permissions="{ permission: ['system:user:transfer'] }"
                    type="info"
                    plain
                    :icon="Switch"
                    @click="handleTransfer()"
                  >
                    <i class="el-icon-refrigerator" />
                    用户迁移至
                  </el-button>
                  <el-button
                    v-permissions="{ permission: ['system:user:import'] }"
                    type="warning"
                    plain
                    @click="handleImport"
                  >
                    <i class="iconfont-fw ri-upload-2-line" />
                    导入
                  </el-button>
                  <el-button
                    v-permissions="{ permission: ['system:user:export'] }"
                    type="success"
                    plain
                    :loading="exportLoading"
                    @click="handleExport"
                  >
                    <i class="iconfont-fw ri-download-2-line" />
                    导出
                  </el-button>
                </vxe-form-item>
              </vxe-form>
            </template>
            <template #tmBank="{ row }">
              <span style="cursor: pointer" @click="breakTm(row)">
                {{ row.tkmc }}
              </span>
            </template>
            <template #zt="{ row }">
              <el-switch
                v-model="row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="0"
                :inactive-value="1"
                @change="changeStatus(row)"
              />
            </template>
            <template #bottom>
              <el-pagination
                background
                :current-page="queryForm.page"
                :layout="layout"
                :page-size="queryForm.pageSize"
                :total="total"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
              />
            </template>
          </vxe-grid>
        </div>
      </Pane>
    </Splitpanes>
    <edit ref="editRef" @fetch-data="fetchData" />
    <UserMove ref="userMoveRef" @fetch-data="fetchData" />
    <userImportForm ref="userImportForm" @fetch-user="fetchData" />
  </div>
</template>

<script>
  import { Pane, Splitpanes } from 'splitpanes'
  import 'splitpanes/dist/splitpanes.css'
  import { postAction } from '@/api/requestEvents'
  import {
    deleteUsers,
    exportUser,
    getUserPage,
    updateUserStatus,
  } from '@/api/system/user/index'
  import { getDeptPage } from '@/api/system/dept/index'
  import {
    Delete,
    Edit,
    MagicStick,
    Plus,
    Search,
    Switch,
  } from '@element-plus/icons-vue'
  import download from '@/utils/download'

  export default defineComponent({
    name: 'User',
    components: {
      Edit: defineAsyncComponent(() => import('./components/userEdit')),
      UserMove: defineAsyncComponent(() => import('./components/userMove')),
      userImportForm: defineAsyncComponent(
        () => import('./components/userImportForm')
      ),
      Splitpanes,
      Pane,
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const $baseTableHeight = inject('$baseTableHeight')
      const $XEUtils = inject('$XEUtils')
      const $baseLodash = inject('$baseLodash')
      const state = reactive({
        deptRef: null,
        editRef: null,
        userMoveRef: null,
        userImportForm: null,
        height: $baseTableHeight(0),
        xGrid: 'xGrid',
        tableColumn: [
          { type: 'checkbox', width: 50, fixed: 'left' },
          { type: 'seq', width: 50, fixed: 'left' },
          {
            field: 'nickname',
            title: '用户昵称',
            showOverflow: true,
            width: 120,
            fixed: 'left',
          },
          {
            field: 'username',
            title: '账号',
            showOverflow: true,
            width: 230,
            fixed: 'left',
          },
          {
            field: 'pwd',
            title: '登录密码',
            showOverflow: true,
            width: 140,
          },
          {
            field: 'unitName',
            title: '所属单位',
            width: 160,
          },
          {
            field: 'deptName',
            title: '处室/部门',
            width: 160,
          },
          {
            field: 'mobile',
            title: '手机号码',
            showOverflow: true,
            width: 120,
          },
          {
            field: 'createTime',
            title: '创建时间',
            showOverflow: true,
            width: 160,
            formatter: ['formatDate', 'yyyy-MM-dd HH:mm:ss'],
          },
          {
            field: 'status',
            title: '状态',
            showOverflow: true,
            fixed: 'right',
            width: 100,
            slots: {
              default: 'zt',
            },
          },
        ],
        statusList: [
          { key: 0, display_name: '启用' },
          { key: 1, display_name: '停用' },
        ],
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          pageNo: 1,
          pageSize: 30,
          username: undefined,
          mobile: undefined,
          status: undefined,
          deptId: undefined,
        },
        exportLoading: false,
      })

      const handleEdit = (but) => {
        if (but === 'edit') {
          const xGridUser = state['xGrid'].getCheckboxRecords()
          if (xGridUser.length === 0 || xGridUser.length > 1) {
            $baseMessage('请选择一条记录', 'error')
          }
          if (xGridUser.length == 1) {
            state['editRef'].showEdit(xGridUser[0])
          }
        } else {
          state['editRef'].showEdit({})
        }
      }

      const handleTransfer = () => {
        const rows = state['xGrid'].getCheckboxRecords()
        if (rows.length > 0) {
          rows.forEach((item) => {
            item.orgNodeList = []
          })
          state['userMoveRef'].showEdit(rows)
        } else {
          $baseMessage(
            '请选择要移动的用户列表',
            'error',
            'vab-hey-message-error'
          )
        }
      }

      const handleDelete = () => {
        const rows = state['xGrid'].getCheckboxRecords()
        if (rows.length > 0) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await deleteUsers($baseLodash.map(rows, 'id'))
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            await fetchData()
          })
        } else {
          $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
        }
      }

      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }

      const handleCurrentChange = (val) => {
        state.queryForm.pageNo = val
        fetchData()
      }

      const queryData = () => {
        const orgchk = state.deptRef.getCheckedNodes()
        state.queryForm.orgNodeList = []
        orgchk.forEach((item) => {
          state.queryForm.orgNodeList.push(item.value)
        })
        state.queryForm.pageNo = 1
        fetchData()
      }

      const fetchData = async (val) => {
        state.listLoading = true
        getUserPage(state.queryForm)
          .then((res) => {
            if (res.code == 0 || res.code == 200) {
              state['xGrid'].reloadData(res.data.list)
              state.total = res.data.total
              state.listLoading = false
            } else {
              state.listLoading = false
            }
          })
          .catch((err) => {
            state.listLoading = false
          })
      }

      const loadNode = (node, resolve) => {
        if (node.level === 0) {
          getList(node, resolve, '0')
        }
        if (node.level >= 1) {
          getList(node, resolve, node.data.id)
        }
      }

      const getList = (node, resolve, id) => {
        state.lazyLoading = true
        getDeptPage({
          parentId: id,
        })
          .then((response) => {
            state.lazyLoading = false
            if (response.code === 0 || response.code === 200) {
              response.data.forEach((item) => {
                item.children = []
              })
              const data = $XEUtils.toArrayTree(response.data, {
                parentKey: 'parentId',
                key: 'id',
                children: 'childNode',
              })
              return resolve(Object.assign([], data))
            } else {
              $baseMessage(response.msg, 'error')
            }
          })
          .catch((err) => {
            state.lazyLoading = false
          })
      }

      const seqMethod = ({ row, rowIndex, column, columnIndex }) => {
        return (
          (state.queryForm.pageNo - 1) * state.queryForm.pageSize + rowIndex + 1
        )
      }

      const changeStatus = (val) => {
        updateUserStatus(val.id, val.status).then((response) => {
          if (response.code === 0 || response.code === 200) {
            $baseMessage(response.msg, 'success', 'vab-hey-message-success')
          } else {
            $baseMessage(response.msg, 'error', 'vab-hey-message-success')
          }
        })
      }

      const pwdReset = () => {
        const row = state['xGrid'].getCheckboxRecords()
        row.forEach((item) => {
          item.orgNodeList = []
        })
        if (row.length > 0) {
          $baseConfirm('确要重置当前选择中的用户密码吗？', null, async () => {
            state.listLoading = true
            postAction('/api/system/user/batchUpdatePwd', {
              userList: row,
            })
              .then((response) => {
                if (response.code === 200) {
                  fetchData()
                  $baseMessage('重置完成', 'success', 'vab-hey-message-success')
                } else {
                  $baseMessage(
                    response.message,
                    'error',
                    'vab-hey-message-success'
                  )
                }
              })
              .catch(() => {
                state.listLoading = false
              })
          })
        } else {
          this.$baseMessage('请先选择行！', 'error')
          return
        }
      }
      const handleImport = () => {
        state['userImportForm'].showEdit()
      }

      const handleExport = async () => {
        state.exportLoading = true
        const data = await exportUser(state.queryForm)
        download.excel(data, '用户数据.xls')
        state.exportLoading = false
      }

      const handleNodeClick = (val) => {
        state.queryForm.deptId = val.id
        fetchData()
      }

      onMounted(() => {
        fetchData()
      })

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })

      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })

      const handleHeight = () => {
        state.height = $baseTableHeight(0)
      }

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        changeStatus,
        handleExport,
        handleSizeChange,
        handleCurrentChange,
        handleTransfer,
        loadNode,
        queryData,
        fetchData,
        seqMethod,
        pwdReset,
        Delete,
        Plus,
        Search,
        Edit,
        Switch,
        MagicStick,
        handleNodeClick,
        handleImport,
      }
    },
  })
</script>
